/**
    ATClab - scriptable Air Traffic Control simulations.
    Copyright (C) 2010 openatclab@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

#include "intersectionpoint.h"
#include <qpoint.h>

//-----------------------------------------------------------------------------

/*!
 *
 */
atc::IntersectionPoint::IntersectionPoint(
	const QPoint &p1, const QPoint &p2,
	const QPoint &p3, const QPoint &p4
){
	_u_denominator =
		(p4.y() - p3.y()) * (p2.x() - p1.x()) -
		(p4.x() - p3.x()) * (p2.y() - p1.y());

	_ua_numerator = 
		(p4.x() - p3.x()) * (p1.y() - p3.y()) -
		(p4.y() - p3.y()) * (p1.x() - p3.x());

	_ub_numerator = 
		(p2.x() - p1.x()) * (p1.y() - p3.y()) -
		(p2.y() - p1.y()) * (p1.x() - p3.x());

	if(_u_denominator){
		double ua = (_ua_numerator / _u_denominator);
		_x = (int)( p1.x() + ua * (p2.x() - p1.x()) );
		_y = (int)( p1.y() + ua * (p2.y() - p1.y()) );
	}
}

/*!
 *
 */
atc::IntersectionPoint::~IntersectionPoint()
{}

//-----------------------------------------------------------------------------

/*!
 *
 */
bool atc::IntersectionPoint::parallel()const{
	return !_u_denominator;
}

/*!
 *
 */
bool atc::IntersectionPoint::coincident()const{
	return parallel() && !_ua_numerator && !_ub_numerator;
}

/*!
 *
 */
QPoint atc::IntersectionPoint::point()const
{
	if(parallel())
		throw atc::intersectionpoint_error(
			"lines are parallel"
		);

	return QPoint(_x, _y);
}

//-----------------------------------------------------------------------------
